package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE,
            key = "#pageNum + '-' + #pageSize + '-' + #query.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO query, int pageNum, int pageSize) {
        //sql：select * from safeguard where safeguard_key = ? and safeguardKeyName like ? and data_state = 0
        //构建queryWrapper查询条件
        LambdaQueryWrapper<Safeguard> safeguardLambdaQueryWrapper = this.initWrapper(query);
        //分页查询
        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), safeguardLambdaQueryWrapper);
        //PO转VO
        return BeanConv.toPage(page, SafeguardVO.class);
    }

    private LambdaQueryWrapper<Safeguard> initWrapper(SafeguardVO query) {
        LambdaQueryWrapper<Safeguard> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(query.getSafeguardKey()), Safeguard::getSafeguardKey, query.getSafeguardKey());
        lqw.like(StrUtil.isNotBlank(query.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, query.getSafeguardKeyName());
        lqw.eq(StrUtil.isNotBlank(query.getDataState()), Safeguard::getDataState, query.getDataState());
        return lqw;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC, key = "#safeguardId")
    public SafeguardVO findById(String safeguardId) {
        Safeguard safeguard = lambdaQuery().eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0)
                .one();
        SafeguardVO bean = BeanConv.toBean(safeguard, SafeguardVO.class);
        return bean;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    //判断是否加事务注解
    //1.是否有多次写的操作
    //2.如果只有一次写的操作，写操作时候是否还有代码
    @Caching(put = @CachePut(value = SafeguardCacheConstant.BASIC, key = "#result.id"),
            evict = {
                    @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)
            })
    public SafeguardVO save(SafeguardVO safeguardVO) {
        Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
        //key不能重复
        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count > 0) {
            log.error("新增保障项失败，KEY已存在：{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        boolean saveForSafeguard = this.save(safeguard);
        if (!saveForSafeguard) {
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }


    @Autowired
    private ICategorySafeguardService categorySafeguardService;
    @Autowired
    private IPlanSafeguardService planSafeguardService;

    /**
     * 保障项修改
     *
     * @param safeguardVO 保障项对象
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(
            evict = {
                    @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id"),
            })
    public Boolean update(SafeguardVO safeguardVO) {
        //1.先查数据库数据存在才能修改
        Safeguard safeguard = getById(safeguardVO.getId());
        if (safeguard == null) {
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //2.判断保障项编码是否存在，存在不允许修改
        //select count(*) from tab where id != ? and key =?
        Integer count = lambdaQuery().eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .ne(Safeguard::getId, safeguardVO.getId())
                .count();
        if (count > 0) {
            log.error("修改保障项失败，KEY已存在：{}", safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //3.有关联关系，不能修改tab_categoary_safeguard  tab_plan_safeguard
        Integer count1 = categorySafeguardService.lambdaQuery().eq(CategorySafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                .count();
        Integer count2 = planSafeguardService.lambdaQuery().eq(PlanSafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("当前保障项绑定其他关系，不可修改！");
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //4.修改
        Safeguard safeguard2 = BeanConv.toBean(safeguardVO, Safeguard.class);
        safeguard2.setUpdateBy(null);
        safeguard2.setUpdateTime(null);
        return this.updateById(safeguard2);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(
            evict = {
                    @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true),
            })
    public Boolean delete(String[] checkedIds) {
        //1.先判断删除项是否都存在
        for (String checkedId : checkedIds) {
            Safeguard safeguard = getById(checkedId);
            if (safeguard == null) {
                log.error("删除项不存在，保障项id为:{}", checkedId);
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
            //2.判断是否有关联关系，有关联关系不可以删除
            Integer count1 = categorySafeguardService.lambdaQuery().eq(CategorySafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                    .count();
            Integer count2 = planSafeguardService.lambdaQuery().eq(PlanSafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                    .count();
            if (count1 > 0 || count2 > 0) {
                log.error("当前保障项绑定其他关系，不可修改！");
                throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
            }
            //3.删除
            boolean result = removeById(checkedId);
            if (!result) {
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
        }
        return true;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST, key = "#safeguardVO.id")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        LambdaQueryWrapper<Safeguard> lqw = initWrapper(safeguardVO);
        List<Safeguard> list = this.list(lqw);
        return BeanConv.toBeanList(list, SafeguardVO.class);
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }
}
